let config = require('../../../config/config.js')
var QQMapWx = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({ key: config.map_key })
let request = require("../../../utils/request.js"); //封装的request请求
const app = getApp() //获取应用实例
let flag = true

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    parkInfo: Object,
    longitude: Number,
    latitude: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
    parkInfo: {},
    parkImgCurr: 0
  },

  lifetimes: {
    attached: function() {
      console.log('在组件实例进入页面节点树时执行')
      this.getParkInfo()
    },
    detached: function() {
      console.log('在组件实例被从页面节点树移除时执行')
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取停车场详情
     */
    getParkInfo(){
      this.calculateDistance(
        { longitude: this.data.longitude, latitude: this.data.latitude },
        [ { longitude: this.data.parkInfo.longitude, latitude: this.data.parkInfo.latitude } ],
        (res)=> {
          let distances = (res.result.elements[0].distance / 1000).toFixed(2)
          console.log(distances);
          request.http(
            '/park/info/getParkInfoById', 
            'GET', 
            { parkId: this.data.parkInfo.id }
          ).then(parkRes => {
            let data = parkRes.data
            if (data.code == 200) {
              let parkInfo = data.data
              parkInfo['distances'] = distances
              parkInfo['id'] = this.data.parkInfo.id
              let parkImgUrls = [];
              let arr = [];
              //暂时做的判断   没图片时 先随便放一个图片
              if(parkInfo.parkImgUrl){
                parkInfo.parkImgUrl.split(',').forEach((parkImgUrl)=>{
                  arr.push(parkImgUrl)
                  let index = parkImgUrl.split(',')[0].lastIndexOf(".")
                  let name = parkImgUrl.split(',')[0].substr(0, index)
                  let ext = parkImgUrl.split(',')[0].substr(index+1)
                  // parkImgUrl = name + '@_@350.' + ext
                  parkImgUrl = name + '.' + ext
                  parkImgUrls.push(parkImgUrl)
                })
                parkInfo.parkImgUrls = parkImgUrls;
                parkInfo.originalImgArr = arr;
              }else{
                parkInfo.parkImgUrls = ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017bcb58b4db5fa801219c7719b5ff.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631772791&t=f97c88d0443ed9fe68c2ee2a27ee5096'];
              }
              console.log('停车场信息：', parkInfo)
              this.setData({ parkInfo: parkInfo })
            }
          })
        }
      )
    },
    /**
     * 图片预览
    */
    showImage(e) {
      let index = e.currentTarget.dataset.index;
      wx.previewImage({
        urls: this.data.parkInfo.originalImgArr,
        current: this.data.parkInfo.originalImgArr[index]
      })
      console.log(this.data.parkInfo.originalImgArr[index],this.data.parkInfo.originalImgArr)
    },
    /**
     * 图片切换
     */
    parkImgChange(e) {
      this.setData({
        parkImgCurr: e.detail.current
      })
    },
    /**
     * 触底加载
     */
    scrollTolower() {
      if (!flag) {
        return
      }
      flag = false
      this.setData({
        page: this.data.page + 1
      })
      this.getNearbyPark(this.data.longitude, this.data.latitude)
    },
    /**
     * 跳转到购买会员卡页面
     */
    toBuyCard(e) {
      // wx.showToast({
      //   icon:'none',
      //   title: '尽请期待',
      // })
      if (wx.getStorageSync('token')) {
        wx.navigateTo({
          url: '/pages/pay/monthly/monthly?parkData=' + encodeURIComponent(JSON.stringify(this.data.parkInfo))
        })
      } else {
        //  获取用户信息
        this.getUserProfile( '/pages/pay/monthly/monthly?parkData=' + encodeURIComponent(JSON.stringify(this.data.parkInfo)) )
      }
    },
    /**
     * 在地图中打开
     */
    toMapNavigation(e) {
      wx.openLocation({
        latitude: Number(this.data.parkInfo.latitude),
        longitude: Number(this.data.parkInfo.longitude),
        name: this.data.parkInfo.parkName,
        address: this.data.parkInfo.parkAddress,
        scale: 14
      })
    },
    /**
     * 计算两点之间距离
     * @param {Object} from 起始位置经纬度
     * @param {Array} to 终点位置经纬度
     * @param {Function} callback 回调函数
     */
    calculateDistance(from, to, callback) {
      if (to.length <= 0) {
        return
      }
      qqmapsdk.calculateDistance({
        mode: 'driving',
        from,
        to,
        success(res) {
          callback(res)
        },
        fail: function (error) {
          console.error(error);
        },
      })
    },
    /**
     * 跳转到预约页面
     */
    toReserve(e) {
      console.log('跳转到预约页面：', e)

      if (this.data.parkInfo.reserveParkSpace == 0) {
        wx.showToast({ title: '当前可预约车位为0，请选择其他停车场', icon: 'none' })
        return
      }

      if (wx.getStorageSync('token')) {
        wx.navigateTo({
          url: '/pages/subscribe/subscribe?parkId=' + this.data.parkInfo.id + '&parkName=' + this.data.parkInfo.parkName
        })
      } else {
        //  获取用户信息
        this.getUserProfile( '/pages/subscribe/subscribe?parkId=' + this.data.parkInfo.id + '&parkName=' + this.data.parkInfo.parkName )
      }
    },
    /**
     * 跳转到领取停车券页面
     */
    toReceiveTicket(e) {
      console.log('跳转到领取停车券页面：', e)
      if (wx.getStorageSync('token')) {
        wx.navigateTo({ url: '/pages/park-ticket/parkTicket?parkId=' + this.data.parkInfo.id })
      } else {
        //  获取用户信息
        this.getUserProfile( '/pages/park-ticket/parkTicket?parkId=' + this.data.parkInfo.id )
      }
    },
    /**
     * 跳转到夜间卡页面
     */
    toReceiveMabi(e) {
      // wx.showToast({
      //   icon:'none',
      //   title: '尽请期待',
      // })
      if (wx.getStorageSync('token')) {
        wx.navigateTo({
          url: '../pay/nightCard/nightCard?parkData=' + encodeURIComponent(JSON.stringify(this.data.parkInfo))
        })
      } else {
        //  获取用户信息
        this.getUserProfile( '../pay/nightCard/nightCard?parkData=' + encodeURIComponent(JSON.stringify(this.data.parkInfo)) )
      }
    },
    /**
     * 关闭弹窗
     */
    bottomPopClose(){
      this.triggerEvent('bottomPopClose')
    },
    /**
     * 授权
     */
    getUserProfile(e){
      this.triggerEvent('getUserProfile', e)
    }
  }
})